package br.ufba.lasid.jitclouds.mda.queue;

import br.ufba.lasid.jitclouds.mda.utils.MQProperties;
import br.ufba.lasid.jitclouds.mda.vo.MDA;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TDeserializer;

public class Receiver {

    private static final String EXCHANGE_NAME = "vm_metric";
    private static final String EXCHANGE_TYPE = "topic";

    public static void main(String[] args) throws Exception {

        String ip = StringUtils.EMPTY;
        String port = StringUtils.EMPTY;
        String queue = StringUtils.EMPTY;
        boolean flagGood = false;
        // obtém uma conexão para acesso ao servidor AMQP
        ConnectionFactory factory = new ConnectionFactory();

        if (args != null && args.length > 0) {

            for (int i = 0; i < args.length; i++) {
                String string = args[i];

                if (StringUtils.equals("-ip", string) && args.length >= (i + 2)) {
                    ip = args[i + 1];
                } else if (StringUtils.equals("-port", string) && args.length >= (i + 2)) {
                    port = args[i + 1];
                } else if (StringUtils.equals("-queue", string) && args.length >= (i + 2)) {
                    queue = args[i + 1];
                }
            }
            if (StringUtils.isEmpty(ip) || StringUtils.isBlank(port) || StringUtils.isBlank(queue)) {
                System.out.println("You should type the parameter and the values:");
                System.out.println("-ip value -port value -queue value");
                System.out.println("-ip 192.168.188.9 -port 5672 -queue vm_metric");
                flagGood = false;
            } else {
                flagGood = true;
                System.out.println("Reading parameters from shell [" + ip + ":" + port + "] at queue: " + queue);
                factory.setHost(ip);
                factory.setPort(Integer.parseInt(port));
            }
        } else {
            System.out.println("Reading parameters from properties file [" + MQProperties.get(MQProperties.HOST) + ":" + MQProperties
                    .get(MQProperties.PORT) + "]");
            factory.setHost(MQProperties.get(MQProperties.HOST));
            factory.setPort(Integer.parseInt(MQProperties
                    .get(MQProperties.PORT)));
            queue = EXCHANGE_NAME;
        }

        if (flagGood) {
            Connection connection = factory.newConnection();

            // obtém uma canal, uma forma de multiplexar uma mesma conexão
            Channel channel = connection.createChannel();

            // channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
            channel.queueDeclare(queue, false, false, false, null);

            // fila onde ficarão as mensagens recebidas
            String queueName = channel.queueDeclare().getQueue();

            System.out
                    .println(" [*] Waiting for metric observations. To exit press CTRL+C");

            QueueingConsumer consumer = new QueueingConsumer(channel);
            // channel.basicConsume(queueName, true, consumer);
            // Register the consumer on the channel
            channel.basicConsume(queue, true, consumer);

            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();

                MDA item = new MDA();
                // Instantiate the Thrift Deserializer
                TDeserializer deserializer = new TDeserializer();
                // Deserialize the body of the AMQP message, setting the state
                // on the empty notification object
                deserializer.deserialize(item, delivery.getBody());

                // Print the notification to the console.
                System.out.println(" [x] Received '" + item.toString() + "'");
            }
            // channel.close();
            // connection.close();
        }
    }
}
